﻿using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace WpfTransformTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += OnLoaded;
        }

        private List<Image> _images = new List<Image>();
        private Dictionary<UdpSession, Image> _clientAndImages = new Dictionary<UdpSession, Image>();
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            _images = new List<Image>() { Image1, Image2, Image3, Image4, Image5,Image6 };
            _clientAndImages.Clear();

            var port = 8000;
            for (int i = 0; i < 5; i++)
            {
                port += 1;
                var udpSession = new UdpSession();
                udpSession.Setup(new TouchSocketConfig()
                    .SetBindIPHost(new IPHost($"127.0.0.1:{port}"))
                    .SetUdpDataHandlingAdapter(() => new UdpPackageAdapter()));//加载配置
                udpSession.Start();//启动
                _clientAndImages.Add(udpSession, _images[i]);
                udpSession.Received += (s,data ) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        _clientAndImages[udpSession].Source = ByteArrayToBitmapImage(data.ByteBlock.Span.ToArray());
                    });
                    return EasyTask.CompletedTask;
                };
            }
        }
        private BitmapImage ByteArrayToBitmapImage(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                return null;

            var bitmapImage = new BitmapImage();
            using (var stream = new System.IO.MemoryStream(bytes))
            {
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
            }

            bitmapImage.Freeze(); // 冻结对象以提高性能（线程安全）
            return bitmapImage;
        }
    }
}